package com.lianda.mutiple.pattern.future;

public class FutureTask<T> implements Future<T> {

    //计算结果
    private T result;

    //任务是否完成
    private boolean isDone = false;

    //对象锁
    private final Object LOCK = new Object();


    @Override
    public T get() throws InterruptedException {
        synchronized (LOCK) {
            //循环判断任务是否完成
            while (!isDone) {
                LOCK.wait();
            }
        }
        return result;
    }

    //设置结果
    protected void finish(T result) {
        synchronized (LOCK) {
            //balking设计模式
            if (isDone)
                return;
            this.result = result;
            this.isDone = true;
            LOCK.notifyAll();
        }
    }

    @Override
    public boolean done() {
        return isDone;
    }
}
